﻿using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System;

public class BuildVersionFile {

	[MenuItem("Window/Build Version File")]
	public static void BuildeVersionFile() {
		Hashtable verTab = new Hashtable ();
		verTab ["version"] = "1";

		ArrayList files = new ArrayList ();
		verTab ["files"] = files;

        ProcessDir(new DirectoryInfo(Baiyy.Config.streamAssetsPath), files);

		string verStr = MiniJSON.JsonEncode (verTab);
		StreamWriter sw = new StreamWriter (
			Baiyy.Config.streamAssetsPath + "/" + Baiyy.Config.versionFileName);
		sw.Write (verStr);
		sw.Flush ();
		sw.Close ();

		Debug.Log ("Version 文件生成完毕");
	}

    static void ProcessDir(DirectoryInfo dirInfo, ArrayList files) {
        foreach (FileInfo fileInfo in dirInfo.GetFiles()) {
            if ((fileInfo.Name.IndexOf(".ab") == -1
                && fileInfo.Name.IndexOf(".bytes") == -1) || (
                fileInfo.Name.IndexOf(".meta") != -1
                || fileInfo.Name.IndexOf(".manifest") != -1
				|| fileInfo.Name == Baiyy.Config.versionFileName)) {
                continue;
            }

            string resName;
            if (dirInfo.Name != "StreamingAssets") {
                resName = "/" + dirInfo.Name + "/" + fileInfo.Name;
            } else {
                resName = "/" + fileInfo.Name;
            }
            string resMd5 = Md5(fileInfo.FullName);

            Hashtable resItem = new Hashtable();
            resItem["name"] = resName;
            resItem["md5"] = resMd5;

            files.Add(resItem);
        }

        foreach (DirectoryInfo di in dirInfo.GetDirectories()) {
            ProcessDir(di, files);
        }
    }

	static MD5 md5 = MD5.Create ();

	/// <summary>
	/// 计算文件MD5。
	/// </summary>
	/// <param name="fileName">File name.</param>
	static string Md5(string fileName) {
		byte[] data = File.ReadAllBytes (fileName);
		byte[] output = md5.ComputeHash (data);
		string md5Str = "";
		for (int i = 0; i < output.Length; ++i) {
			md5Str += output [i].ToString ("X");
		}
		return md5Str;
	}
}
